import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:wan_android_flutter/pages/personal/person_vm.dart';
import 'package:wan_android_flutter/routes/RouteUtils.dart';
import 'package:wan_android_flutter/routes/routes.dart';

import '../../common_ui/dialog/BottomActionSheet.dart';
import '../../utils/ImagePickerUtils.dart';
import '../../common_ui/dialog/dialog_factory.dart';
import '../../service/CameraService.dart';

class PerSonalPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _PerSonalState();
  }
}

class _PerSonalState extends State<PerSonalPage> {
  PersonViewModel viewModel = PersonViewModel();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    viewModel.initData();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return ChangeNotifierProvider(
        create: (create) {
          return viewModel;
        },
        child: Scaffold(
          body: SafeArea(
              child: Column(
            children: [
              _header(
                  onTap: () {
                    if (viewModel.shouldLogin == true) {
                      RouteUtils.pushForNamed(context, RoutesPath.loginPage);
                    }
                  },
                  modify_avatar: () {
                    _showAvatarMenu(context);
                  },
                  path: viewModel.headImagePath ?? ""),
              _settingsItems(
                  title: "我的收藏",
                  onTap: () {
                    RouteUtils.pushForNamed(context, RoutesPath.myCollectsPage);
                  }),
              _settingsItems(
                  title: "检查更新",
                  onTap: () {
                    checkAppUpdate();
                  }),
              _settingsItems(
                  title: "关于我们",
                  onTap: () {
                    RouteUtils.pushForNamed(context, RoutesPath.aboutUsPage);
                  }),
              viewModel.shouldLogin == true
                  ? SizedBox()
                  : _settingsItems(
                      title: "退出登录",
                      onTap: () {
                        viewModel.loginOut((flag) {
                          if (flag == true) {
                            RouteUtils.pushNamedAndRemoveUntil(
                                context, RoutesPath.loginPage);
                          }
                        });
                      }),
            ],
          )),
        ));
  }

  void _showAvatarMenu(BuildContext context) {
    showModalBottomSheet(
      context: context,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (_) => BottomActionSheet(
        items: [
          ActionSheetItem(
              title: '手机拍摄',
              onTap: () async {
                String? path = await CameraServicePlugin.takePicture();
                viewModel.updateHeadImagePath(path);
              }),
          ActionSheetItem(
            title: '从相册选择',
            // icon: Icons.photo_library,
            onTap: () {
              ImagePickerUtils.pickImageFromGallery(context, (value) {
                print(value);
                viewModel.updateHeadImagePath(value);
              });
            },
          ),
          ActionSheetItem(
            title: '取消',
            isCancel: true,
            onTap: () => print('取消'),
          ),
        ],
      ),
    );
  }

  Widget _settingsItems({String? title, GestureTapCallback? onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: EdgeInsets.only(left: 15.w, right: 15.w, top: 15.h),
        padding: EdgeInsets.only(left: 15.w, right: 15.w),
        width: double.infinity,
        height: 40.h,
        decoration: BoxDecoration(
            border: Border.all(color: Colors.black, width: 0.5.r),
            borderRadius: BorderRadius.all(Radius.circular(5.r))),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              title ?? "",
              style: TextStyle(fontSize: 13.sp, color: Colors.black),
            ),
            Image.asset(
              "assets/images/img_arrow_right.png",
              width: 20.r,
              height: 20.r,
            )
          ],
        ),
      ),
    );
  }

  Widget _header(
      {GestureTapCallback? onTap,
      GestureTapCallback? modify_avatar,
      String? path}) {
    return Consumer<PersonViewModel>(builder: (context, vm, child) {
      return Container(
          alignment: Alignment.center,
          color: Colors.teal,
          width: double.infinity,
          height: 200.h,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              GestureDetector(
                onTap: modify_avatar,
                child: Consumer<PersonViewModel>(
                  builder: (context, vm, child) {
                    // 使用 UUID 来确保每次渲染都不一样
                    var uniqueKey = DateTime.now().toString();  // 或者使用 DateTime.now().toString()

                    return ClipRRect(
                      borderRadius: BorderRadius.circular(35.r),
                      child: vm.headImagePath?.isNotEmpty == true
                          ? Image.file(
                        File(vm.headImagePath!),
                        key: Key(uniqueKey),  // 关键的一行，确保每次都不一样
                        width: 70.r,
                        height: 70.r,
                        fit: BoxFit.cover,
                      )
                          : Image.asset(
                        "assets/images/logo.png",
                        key: Key(uniqueKey),  // 关键的一行，确保每次都不一样
                        width: 70.r,
                        height: 70.r,
                      ),
                    );
                  },
                ),
              ),
              SizedBox(
                height: 6.h,
              ),
              GestureDetector(
                  onTap: onTap,
                  child: Text(
                    vm.username ?? "未登录",
                    style: TextStyle(color: Colors.white, fontSize: 13.sp),
                  )),
            ],
          ));
    });
  }

  ///检查更新
  void checkAppUpdate() {
    viewModel.checkUpdate().then((url) {
      if (url != null && url.isNotEmpty == true) {
        DialogFactory.instance.showNeedUpdateDialog(
            context: context,
            dismissClick: () {
              //是否显示更新红点
              viewModel.shouldShowUpdateDot();
            },
            confirmClick: () {
              //跳转到外部浏览器打开
              viewModel.jumpToOutLink(url);
            });
      } else {
        showToast("已是最新版本");
      }
    });
  }
}
